package com.comunity_cloud.client.model.communication;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;

import net.rudp.ReliableServerSocket;

public class Host extends Thread{

	private ReliableServerSocket serverSocket;
	private DatagramPacket packet= new DatagramPacket(new byte[1], 1);

	public Host() throws IOException {
		serverSocket = new ReliableServerSocket(0);
	}
	
	@Override
	public void run() {
		while(true) {
			try {
				Socket sock = serverSocket.accept();
				InputStream inputStream = sock.getInputStream();
				
				byte[] clientIdBytes = new byte[8];
				inputStream.read(clientIdBytes);
				
				long clientId = ByteBuffer.wrap(clientIdBytes).getLong();
				System.out.println("Connection from "+clientId);
				PeerConnection connection = new PeerConnection(sock);
				connection.setClientId(clientId);
				connection.start();
				ConnectionsManager.getInstance().addConnction(connection);				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void openPinhole(String ip, int port) throws IOException {
		packet.setAddress(InetAddress.getByName(ip));
		packet.setPort(port);
		serverSocket.getServerSock().send(packet);
	}
	
	public int getPort(){
		return serverSocket.getLocalPort();
	}
	
}
